package com.littleken.controller;

import com.littleken.entity.User;
import com.littleken.service.UserService;
import com.littleken.service.impl.UserServiceImpl;
import com.littleken.util.JsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * login servlet
 */
@WebServlet("/login")
public class LoginServlet  extends HttpServlet {
    UserService service = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");//用户传送过来的用户名
        String password = req.getParameter("password");//用户传送过来的密码
        String code = req.getParameter("code").toLowerCase();//用户传送过来的code,转为小写
        HttpSession session = req.getSession();
        String rand = ((String) session.getAttribute("rand")).toLowerCase();//session中的验证码转为小写

        System.out.println(username);
        System.out.println(password);
        System.out.println("code:" + code);
        System.out.println("rand:" + rand);
        String message= "";
        User checkUser = null;

        if (!rand.equals(code)){
            message = JsonData.fail("验证码有误").toString();
            resp.getWriter().append(message);
        }else {
            checkUser = User.builder().Username(username).Password(password).build();
            User user = service.checkUser(checkUser);
            if (user == null) {
                message = JsonData.fail("用户名或密码有误").toString();
                System.out.println(message);
                resp.getWriter().append(message);
            }else{
                session.setAttribute("user",user);
                message = JsonData.success("successTest").toString();//todo：把写死在jsp的主页地址改成这里发送过去
                System.out.println(message);
                resp.getWriter().append(message);
            }
        }
    }
}
